import axios from 'axios'
import router from '../router'

// 创建axios实例
const http = axios.create({
  baseURL: '/api',  // 使用Vite代理配置
  timeout: 10000
})

// 请求拦截器
http.interceptors.request.use(
  config => {
    // 从本地存储获取token
    const token = localStorage.getItem('token') || localStorage.getItem('access_token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    const { status } = error.response || {}
    
    // 处理401未授权错误
    if (status === 401) {
      // 清除本地存储的token和用户信息
      localStorage.removeItem('token')
      localStorage.removeItem('access_token')
      localStorage.removeItem('user')
      
      // 如果不是登录页面，则重定向到登录页
      if (router.currentRoute.value.name !== 'Login') {
        router.push({
          name: 'Login',
          query: { redirect: router.currentRoute.value.fullPath }
        })
      }
    }
    
    // 返回错误信息
    return Promise.reject(error)
  }
)

export default http